// 通知管理页面
const { createNotice, getNotices, getNoticeStats, updateNoticeStatus, deleteNotice, updateNotice } = require('../../../api/notice');
const { getCurrentUser } = require('../../../utils/auth');

Page({
  data: {
    loading: false,
    notices: [],
    allNotices: [], // 保存所有原始数据
    currentFilter: 'all', // 当前筛选条件
    stats: {
      totalCount: 0,
      publishedCount: 0,
      draftCount: 0,
      noticeCount: 0,
      financeCount: 0,
      projectCount: 0,
      policyCount: 0,
      activityCount: 0
    },
  // 全局加载状态
  globalLoading: false,
  globalLoadingText: '管理数据加载中...',

  // 显示全局加载
  showGlobalLoading(text = '管理数据加载中...') {
    const app = getApp()
    app.showGlobalLoading({
      loadingText: text
    })
  },

  // 隐藏全局加载
  hideGlobalLoading() {
    const app = getApp()
    app.hideGlobalLoading()
  },

  // 更新全局加载状态
  updateGlobalLoading(data) {
    this.setData({
      globalLoading: data.globalLoading,
      globalLoadingText: data.globalLoadingText || this.data.globalLoadingText
    })
  },
    // 弹窗控制
    showCreateModal: false,
    showEditModal: false,
    currentNotice: null,
    // 表单数据
    formData: {
      title: '',
      content: '',
      type: 'notice',
      dept: '村委会',
      priority: 'normal',
      isUrgent: false,
      icon: '📢'
    },
    // 通知类型选项
    typeOptions: [
      { value: 'notice', label: '通知公告', icon: '📢' },
      { value: 'finance', label: '财务公开', icon: '💰' },
      { value: 'project', label: '项目建设', icon: '🏗️' },
      { value: 'policy', label: '政策文件', icon: '📋' },
      { value: 'activity', label: '活动通知', icon: '🎉' },
      { value: 'urgent', label: '紧急通知', icon: '🚨' }
    ],
    // 优先级选项
    priorityOptions: [
      { value: 'low', label: '低', color: '#10b981' },
      { value: 'normal', label: '普通', color: '#3b82f6' },
      { value: 'high', label: '高', color: '#f59e0b' },
      { value: 'urgent', label: '紧急', color: '#ef4444' }
    ],
    // 图标选项
    iconOptions: [
      { value: '📢', label: '通知' },
      { value: '📋', label: '政策' },
      { value: '🎉', label: '活动' },
      { value: '🚨', label: '紧急' },
      { value: '🔧', label: '维护' },
      { value: '🏥', label: '健康' },
      { value: '💰', label: '补贴' },
      { value: '🏠', label: '住房' },
      { value: '🌾', label: '农业' },
      { value: '📚', label: '教育' }
    ]
  },

  onLoad() {
    console.log('通知管理页面加载成功')
    this.loadNotices()
  },

  onShow() {
    console.log('通知管理页面显示')
  },

  // 加载通知数据
  async loadNotices() {
    console.log('加载通知数据')
    this.setData({ loading: true })
    
    try {
      // 并行获取公告列表和统计数据
      const [noticesResponse, statsResponse] = await Promise.all([
        getNotices({
          page: 1,
          limit: 100,
          type: this.data.currentFilter === 'all' ? 'all' : this.data.currentFilter,
          status: 'all'
        }),
        getNoticeStats()
      ]);

      if (noticesResponse.success && statsResponse.success) {
        const notices = noticesResponse.data.notices || [];
        const stats = statsResponse.data.stats || {};
        
        // 格式化公告数据
        const formattedNotices = notices.map(notice => ({
          id: notice.id,
          title: notice.title,
          content: notice.content,
          type: notice.type,
          typeText: this.getTypeText(notice.type),
          status: notice.status,
          statusText: notice.status === 'published' ? '已发布' : '草稿',
          publishTime: notice.publishTime ? this.formatTime(new Date(notice.publishTime)) : '',
          readCount: notice.readCount || 0,
          dept: notice.dept,
          icon: this.getTypeIcon(notice.type),
          isUrgent: notice.isUrgent || false,
          priority: notice.isUrgent ? 'urgent' : 'normal',
          createTime: this.formatTime(new Date(notice.createTime)),
          updateTime: this.formatTime(new Date(notice.updateTime))
        }));

        this.setData({
          notices: formattedNotices,
          allNotices: formattedNotices,
          stats: {
            totalCount: stats.totalCount || 0,
            publishedCount: stats.publishedCount || 0,
            draftCount: stats.draftCount || 0,
            noticeCount: stats.noticeCount || 0,
            financeCount: stats.financeCount || 0,
            projectCount: stats.projectCount || 0,
            policyCount: stats.policyCount || 0,
            activityCount: stats.activityCount || 0
          },
          loading: false
        });
      } else {
        console.error('获取数据失败:', noticesResponse.message, statsResponse.message);
        wx.showToast({
          title: noticesResponse.message || statsResponse.message || '获取数据失败',
          icon: 'none'
        });
        this.loadMockNotices(); // 降级到数据
      }
    } catch (error) {
      console.error('加载通知数据失败:', error);
      wx.showToast({
        title: '网络连接失败，已加载数据',
        icon: 'none'
      });
      this.loadMockNotices(); // 降级到数据
    }
  },

  // 加载数据
  loadMockNotices() {
    const mockNotices = [
      {
        id: 'n1',
        type: 'notice',
        title: '关于台风预警通知，做好防范准备',
        content: '根据气象部门预报，未来三天将有强台风影响我村。请村民做好防范准备，加固房屋，储备生活物资，减少外出。如有紧急情况请及时联系村委会。',
        status: 'published',
        statusText: '已发布',
        publishTime: '2024-10-05 09:00',
        readCount: 156,
        dept: '村委会',
        icon: '🚨',
        isUrgent: true,
        priority: 'urgent',
        createTime: '2024-10-05 08:30',
        updateTime: '2024-10-05 09:00'
      },
      {
        id: 'n2',
        type: 'finance',
        title: '2024年第三季度村财务收支情况公示',
        content: '现将2024年第三季度村财务收支情况向全体村民公示。收入主要包括上级拨款、村集体经济收入等，支出主要用于基础设施建设、公共服务等。',
        status: 'published',
        statusText: '已发布',
        publishTime: '2024-10-01 10:00',
        readCount: 234,
        dept: '村委会',
        icon: '💰',
        isUrgent: false,
        priority: 'high',
        createTime: '2024-10-01 09:30',
        updateTime: '2024-10-01 10:00'
      },
      {
        id: 'n3',
        type: 'project',
        title: '村内道路维修工程进展通报',
        content: '村内主要道路维修工程已启动，预计工期15天。施工期间请村民绕行，注意安全。工程包括路面修复、排水系统改造等。',
        status: 'draft',
        statusText: '草稿',
        publishTime: '',
        readCount: 0,
        dept: '村委会',
        icon: '🔧',
        isUrgent: false,
        priority: 'normal',
        createTime: '2024-09-25 09:30',
        updateTime: '2024-09-25 09:30'
      }
    ]

    const stats = {
      totalCount: mockNotices.length,
      publishedCount: mockNotices.filter(item => item.status === 'published').length,
      draftCount: mockNotices.filter(item => item.status === 'draft').length,
      noticeCount: mockNotices.filter(item => item.type === 'notice').length,
      financeCount: mockNotices.filter(item => item.type === 'finance').length,
      projectCount: mockNotices.filter(item => item.type === 'project').length,
      policyCount: mockNotices.filter(item => item.type === 'policy').length,
      activityCount: mockNotices.filter(item => item.type === 'activity').length
    }

    this.setData({
      notices: mockNotices,
      allNotices: mockNotices,
      stats: stats,
      loading: false
    })
  },

  // 筛选通知
  onFilterChange(e) {
    const { filter } = e.currentTarget.dataset
    this.setData({ currentFilter: filter })
    
    let filteredNotices = []
    const { allNotices } = this.data
    
    switch(filter) {
      case 'all':
        filteredNotices = allNotices
        break
      case 'notice':
        filteredNotices = allNotices.filter(item => item.type === 'notice')
        break
      case 'finance':
        filteredNotices = allNotices.filter(item => item.type === 'finance')
        break
      case 'project':
        filteredNotices = allNotices.filter(item => item.type === 'project')
        break
      case 'policy':
        filteredNotices = allNotices.filter(item => item.type === 'policy')
        break
      case 'activity':
        filteredNotices = allNotices.filter(item => item.type === 'activity')
        break
    }
    
    this.setData({ notices: filteredNotices })
  },


  // 显示发布通知弹窗
  onShowCreateModal() {
    this.setData({
      showCreateModal: true,
      formData: {
        title: '',
        content: '',
        type: 'notice',
        dept: '村委会',
        priority: 'normal',
        isUrgent: false,
        icon: '📢'
      }
    })
  },

  // 隐藏发布通知弹窗
  onHideCreateModal() {
    this.setData({ showCreateModal: false })
  },

  // 显示编辑通知弹窗
  onShowEditModal(e) {
    const { notice } = e.currentTarget.dataset
    console.log('编辑通知:', notice)
    this.setData({
      showEditModal: true,
      currentNotice: notice,
      formData: {
        title: notice.title || '',
        content: notice.content || '',
        type: notice.type || 'notice',
        dept: notice.dept || '村委会',
        priority: notice.priority || 'normal',
        isUrgent: notice.isUrgent || false,
        icon: notice.icon || '📢'
      }
    })
  },

  // 隐藏编辑通知弹窗
  onHideEditModal() {
    this.setData({ 
      showEditModal: false,
      currentNotice: null
    })
  },

  // 表单输入
  onFormInput(e) {
    const { field } = e.currentTarget.dataset
    const value = e.detail.value
    this.setData({
      [`formData.${field}`]: value
    })
    
    // 如果是内容字段，检查字符数限制
    if (field === 'content' && value.length > 2000) {
      wx.showToast({
        title: '内容不能超过2000字符',
        icon: 'none'
      })
    }
  },

  // 选择通知类型
  onSelectType(e) {
    const { type } = e.currentTarget.dataset
    this.setData({
      'formData.type': type
    })
  },

  // 选择优先级
  onSelectPriority(e) {
    const { priority } = e.currentTarget.dataset
    this.setData({
      'formData.priority': priority
    })
  },

  // 选择图标
  onSelectIcon(e) {
    const { icon } = e.currentTarget.dataset
    this.setData({
      'formData.icon': icon
    })
  },

  // 紧急通知开关
  onUrgentChange(e) {
    this.setData({
      'formData.isUrgent': e.detail.value
    })
  },

  // 提交发布通知
  async onSubmitCreate() {
    const { formData } = this.data
    
    // 表单验证
    if (!formData.title.trim()) {
      wx.showToast({ title: '请输入通知标题', icon: 'none' })
      return
    }
    if (!formData.content.trim()) {
      wx.showToast({ title: '请输入通知内容', icon: 'none' })
      return
    }
    if (formData.content.length > 2000) {
      wx.showToast({ title: '通知内容不能超过2000字符', icon: 'none' })
      return
    }
    if (!formData.dept.trim()) {
      wx.showToast({ title: '请输入发布部门', icon: 'none' })
      return
    }

    try {
      // 获取当前用户信息
      const currentUser = getCurrentUser();
      if (!currentUser) {
                // 数据加载完成，隐藏全局加载
        smartLoadingManager.forceHidePageLoading('pages/admin/notices/index');
        wx.showToast({ title: '用户信息获取失败，请重新登录', icon: 'none' });
        return;
      }

      // 准备请求数据
      const requestData = {
        title: formData.title.trim(),
        content: formData.content.trim(),
        type: formData.type,
        is_urgent: formData.isUrgent || false,
        publisher_id: parseInt(currentUser.userId), // 确保是数字类型
        publisher_name: currentUser.name || '管理员',
        publish_dept: formData.dept.trim()
      };

      console.log('发送发布公告请求:', requestData);

      // 调用API发布公告
      const response = await createNotice(requestData);
      
      if (response.success) {
        const newNotice = {
          id: response.data.notice.id,
          title: response.data.notice.title,
          content: response.data.notice.content,
          type: response.data.notice.type,
          status: response.data.notice.status,
          statusText: '已发布',
          publishTime: this.formatTime(new Date(response.data.notice.publish_time)),
          readCount: response.data.notice.read_count || 0,
          dept: response.data.notice.publish_dept,
          icon: this.getTypeIcon(response.data.notice.type),
          isUrgent: response.data.notice.is_urgent,
          priority: response.data.notice.is_urgent ? 'urgent' : 'normal',
          createTime: this.formatTime(new Date(response.data.notice.created_at)),
          updateTime: this.formatTime(new Date(response.data.notice.updated_at))
        };
        
        const allNotices = [newNotice, ...this.data.allNotices];
        const notices = [newNotice, ...this.data.notices];
        
        // 重新计算统计数据
        const stats = {
          totalCount: allNotices.length,
          publishedCount: allNotices.filter(item => item.status === 'published').length,
          draftCount: allNotices.filter(item => item.status === 'draft').length,
          noticeCount: allNotices.filter(item => item.type === 'notice').length,
          financeCount: allNotices.filter(item => item.type === 'finance').length,
          projectCount: allNotices.filter(item => item.type === 'project').length,
          policyCount: allNotices.filter(item => item.type === 'policy').length,
          activityCount: allNotices.filter(item => item.type === 'activity').length
        };
        
        this.setData({
          allNotices,
          notices,
          stats,
          showCreateModal: false,
          formData: {
            title: '',
            content: '',
            type: 'notice',
            dept: '村委会',
            priority: 'normal',
            isUrgent: false,
            icon: '📢'
          }
        });
        
        wx.showToast({
          title: '发布成功！',
          icon: 'success'
        });
      } else {
        wx.showToast({
          title: response.message || '发布失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('发布公告失败:', error);
            smartLoadingManager.forceHidePageLoading('pages/admin/notices/index');
      wx.showToast({
        title: error.message || '网络错误，请重试',
        icon: 'none'
      });
    }
  },

  // 提交编辑通知
  async onSubmitEdit() {
    const { formData, currentNotice } = this.data
    
    // 表单验证
    if (!formData.title.trim()) {
      wx.showToast({ title: '请输入通知标题', icon: 'none' })
      return
    }
    if (!formData.content.trim()) {
      wx.showToast({ title: '请输入通知内容', icon: 'none' })
      return
    }
    if (formData.content.length > 2000) {
      wx.showToast({ title: '通知内容不能超过2000字符', icon: 'none' })
      return
    }
    if (!formData.dept.trim()) {
      wx.showToast({ title: '请输入发布部门', icon: 'none' })
      return
    }

    try {
      // 获取当前用户信息
      const currentUser = getCurrentUser();
      if (!currentUser) {
        wx.showToast({ title: '用户信息获取失败，请重新登录', icon: 'none' });
        return;
      }

      // 准备请求数据
      const requestData = {
        title: formData.title.trim(),
        content: formData.content.trim(),
        type: formData.type,
        is_urgent: formData.isUrgent || false,
        publisher_name: currentUser.name || '管理员',
        publish_dept: formData.dept.trim()
      };

      console.log('发送编辑公告请求:', requestData);

      // 调用API更新公告
      const response = await updateNotice(currentNotice.id, requestData);
      
      if (response.success) {
        const updatedNotice = {
          ...currentNotice,
          title: response.data.notice.title,
          content: response.data.notice.content,
          type: response.data.notice.type,
          dept: response.data.notice.publish_dept,
          isUrgent: response.data.notice.is_urgent,
          priority: response.data.notice.is_urgent ? 'urgent' : 'normal',
          icon: this.getTypeIcon(response.data.notice.type),
          updateTime: this.formatTime(new Date(response.data.notice.updated_at))
        };
        
        const allNotices = this.data.allNotices.map(item => 
          item.id === currentNotice.id ? updatedNotice : item
        );
        const notices = this.data.notices.map(item => 
          item.id === currentNotice.id ? updatedNotice : item
        );
        
        this.setData({
          allNotices,
          notices,
          showEditModal: false,
          currentNotice: null
        });
        
        wx.showToast({
          title: '保存成功！',
          icon: 'success'
        });
      } else {
        wx.showToast({
          title: response.message || '保存失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('编辑公告失败:', error);
            smartLoadingManager.forceHidePageLoading('pages/admin/notices/index');
      wx.showToast({
        title: error.message || '网络错误，请重试',
        icon: 'none'
      });
    }
  },

  // 格式化时间
  formatTime(date) {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    
    return `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')} ${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`
  },

  // 获取类型图标
  getTypeIcon(type) {
    const iconMap = {
      'notice': '📢',
      'finance': '💰',
      'project': '🏗️',
      'policy': '📋',
      'activity': '🎉',
      'urgent': '🚨'
    };
    return iconMap[type] || '📢';
  },

  // 获取类型文本
  getTypeText(type) {
    const typeMap = {
      'notice': '通知公告',
      'finance': '财务公开',
      'project': '项目建设',
      'policy': '政策文件',
      'activity': '活动通知',
      'urgent': '紧急通知'
    };
    return typeMap[type] || '通知公告';
  },

  // 查看通知详情（点击列表项）
  onViewNoticeDetail(e) {
    const { id } = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/village/notice-detail/index?id=${id}`,
      success: () => console.log('跳转到通知详情页面成功'),
      fail: (err) => {
        console.error('跳转失败:', err)
        wx.showToast({ title: '页面跳转失败', icon: 'none' })
      }
    })
  },

  // 编辑通知
  onEditNotice(e) {
    const { notice } = e.currentTarget.dataset
    console.log('编辑通知:', notice)
    this.setData({
      showEditModal: true,
      currentNotice: notice,
      formData: {
        title: notice.title || '',
        content: notice.content || '',
        type: notice.type || 'notice',
        dept: notice.dept || '村委会',
        priority: notice.priority || 'normal',
        isUrgent: notice.isUrgent || false,
        icon: notice.icon || '📢'
      }
    })
  },

  // 发布公告
  onPublishNotice(e) {
    const { notice } = e.currentTarget.dataset
    wx.showModal({
      title: '确认发布',
      content: `确定要发布"${notice.title}"公告吗？`,
      confirmText: '发布',
      cancelText: '取消',
      confirmColor: '#10b981',
      success: (res) => {
        if (res.confirm) {
          this.publishNotice(notice.id)
        }
      }
    })
  },

  // 执行发布公告
  async publishNotice(id) {
    try {
      const response = await updateNoticeStatus(id, 'published');
      
      if (response.success) {
        const allNotices = this.data.allNotices.map(item => {
          if (item.id === id) {
            return { 
              ...item, 
              status: 'published', 
              statusText: '已发布', 
              publishTime: response.data.notice.publishTime ? this.formatTime(new Date(response.data.notice.publishTime)) : this.formatTime(new Date()),
              updateTime: this.formatTime(new Date(response.data.notice.updateTime))
            }
          }
          return item
        })
        const notices = this.data.notices.map(item => {
          if (item.id === id) {
            return { 
              ...item, 
              status: 'published', 
              statusText: '已发布', 
              publishTime: response.data.notice.publishTime ? this.formatTime(new Date(response.data.notice.publishTime)) : this.formatTime(new Date()),
              updateTime: this.formatTime(new Date(response.data.notice.updateTime))
            }
          }
          return item
        })
        
        // 重新计算统计数据
        const stats = {
          totalCount: allNotices.length,
          publishedCount: allNotices.filter(item => item.status === 'published').length,
          draftCount: allNotices.filter(item => item.status === 'draft').length,
          noticeCount: allNotices.filter(item => item.type === 'notice').length,
          financeCount: allNotices.filter(item => item.type === 'finance').length,
          projectCount: allNotices.filter(item => item.type === 'project').length,
          policyCount: allNotices.filter(item => item.type === 'policy').length,
          activityCount: allNotices.filter(item => item.type === 'activity').length
        }
        
        this.setData({
          allNotices,
          notices,
          stats
        })
        
        wx.showToast({
          title: '发布成功！',
          icon: 'success'
        })
      } else {
        wx.showToast({
          title: response.message || '发布失败',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('发布公告失败:', error);
            smartLoadingManager.forceHidePageLoading('pages/admin/notices/index');
      wx.showToast({
        title: error.message || '网络错误，请重试',
        icon: 'none'
      })
    }
  },

  // 撤回公告
  onUnpublishNotice(e) {
    const { notice } = e.currentTarget.dataset
    wx.showModal({
      title: '确认撤回',
      content: `确定要撤回"${notice.title}"公告吗？`,
      confirmText: '撤回',
      cancelText: '取消',
      confirmColor: '#f59e0b',
      success: (res) => {
        if (res.confirm) {
          this.unpublishNotice(notice.id)
        }
      }
    })
  },

  // 执行取消发布
  async unpublishNotice(id) {
    try {
      const response = await updateNoticeStatus(id, 'draft');
      
      if (response.success) {
        const allNotices = this.data.allNotices.map(item => {
          if (item.id === id) {
            return { 
              ...item, 
              status: 'draft', 
              statusText: '草稿', 
              updateTime: this.formatTime(new Date(response.data.notice.updateTime))
            }
          }
          return item
        })
        const notices = this.data.notices.map(item => {
          if (item.id === id) {
            return { 
              ...item, 
              status: 'draft', 
              statusText: '草稿', 
              updateTime: this.formatTime(new Date(response.data.notice.updateTime))
            }
          }
          return item
        })
        
        // 重新计算统计数据
        const stats = {
          totalCount: allNotices.length,
          publishedCount: allNotices.filter(item => item.status === 'published').length,
          draftCount: allNotices.filter(item => item.status === 'draft').length,
          noticeCount: allNotices.filter(item => item.type === 'notice').length,
          financeCount: allNotices.filter(item => item.type === 'finance').length,
          projectCount: allNotices.filter(item => item.type === 'project').length,
          policyCount: allNotices.filter(item => item.type === 'policy').length,
          activityCount: allNotices.filter(item => item.type === 'activity').length
        }
        
        this.setData({
          allNotices,
          notices,
          stats
        })
        
        wx.showToast({
          title: '取消发布成功！',
          icon: 'success'
        })
      } else {
        wx.showToast({
          title: response.message || '操作失败',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('撤回公告失败:', error);
            smartLoadingManager.forceHidePageLoading('pages/admin/notices/index');
      wx.showToast({
        title: error.message || '网络错误，请重试',
        icon: 'none'
      })
    }
  },

  // 删除通知
  onDeleteNotice(e) {
    const { notice } = e.currentTarget.dataset
    wx.showModal({
      title: '确认删除',
      content: `确定要删除"${notice.title}"通知吗？此操作不可恢复。`,
      confirmText: '删除',
      cancelText: '取消',
      confirmColor: '#ef4444',
      success: (res) => {
        if (res.confirm) {
          this.deleteNotice(notice.id)
        }
      }
    })
  },

  // 执行删除通知
  async deleteNotice(id) {
    try {
      const response = await deleteNotice(id);
      
      if (response.success) {
        const allNotices = this.data.allNotices.filter(item => item.id !== id)
        const notices = this.data.notices.filter(item => item.id !== id)
        
        // 重新计算统计数据
        const stats = {
          totalCount: allNotices.length,
          publishedCount: allNotices.filter(item => item.status === 'published').length,
          draftCount: allNotices.filter(item => item.status === 'draft').length,
          noticeCount: allNotices.filter(item => item.type === 'notice').length,
          financeCount: allNotices.filter(item => item.type === 'finance').length,
          projectCount: allNotices.filter(item => item.type === 'project').length,
          policyCount: allNotices.filter(item => item.type === 'policy').length,
          activityCount: allNotices.filter(item => item.type === 'activity').length
        }
        
        this.setData({
          allNotices,
          notices,
          stats
        })
        
        wx.showToast({
          title: '删除成功！',
          icon: 'success'
        })
      } else {
        wx.showToast({
          title: response.message || '删除失败',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('删除公告失败:', error);
            smartLoadingManager.forceHidePageLoading('pages/admin/notices/index');
      wx.showToast({
        title: error.message || '网络错误，请重试',
        icon: 'none'
      })
    }
  },

  // 下拉刷新
  async onPullDownRefresh() {
    console.log('下拉刷新通知数据');
    try {
      await this.loadNotices();
      wx.showToast({
        title: '刷新成功',
        icon: 'success'
      });
    } catch (error) {
      console.error('刷新失败:', error);
      wx.showToast({
        title: '刷新失败',
        icon: 'none'
      });
    } finally {
      wx.stopPullDownRefresh();
    }
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 空函数，用于阻止事件冒泡
  }
})